import numpy as np


def mean_percentage_error(y_true, y_pred, use_abs=True):
    mask = y_true != 0  # 创建一个掩码，标记实际值不为零的位置
    try:
        if not isinstance(y_true, np.ndarray):
            y_true = np.array(y_true)
        if not isinstance(y_pred, np.ndarray):
            y_pred = np.array(y_pred)

        y_true = y_true.reshape(-1, y_true.shape[-1]) if len(y_true.shape) >= 2 else y_true.reshape(-1, 1)
        y_pred = y_pred.reshape(-1, y_pred.shape[-1]) if len(y_pred.shape) >= 2 else y_pred.reshape(-1, 1)

        if use_abs:
            res = np.mean(np.abs((y_true[mask] - y_pred[mask])/ y_true[mask]))
        else:
            res = np.mean((y_true[mask] - y_pred[mask]) / y_true[mask])
    except Exception as e:
        # print(e)
        raise e

    return res

